import React, {Component,Fragment} from 'react';
import axios from 'axios';
import TodoListItem from "./TodoListItem";
// 父组件通过属性的方式向子组件传递内容
// 子组件通过props接受父组件传递过来的内容
class TodoList extends Component{
    constructor(props) {
        super(props);
        this.state = {
            lists: [
            ],
            inputValue: ''
        };
        this.handleInputValue = this.handleInputValue.bind(this);
        this.handleClick = this.handleClick.bind(this);
        this.handleDelete = this.handleDelete.bind(this);
    }

    componentDidMount() {
        axios.get("/api/todoList")
            .then(res => {
            console.log(res)
        })
            .catch(() => {
                console.log('404')
            })
    }

    handleClick() {

        // this.state.lists.push('1') // 这里的this指向的是button,不绑定this则会报错
        this.setState({
            lists: [...this.state.lists, this.state.inputValue ? this.state.inputValue : '默认项'],
            inputValue: ''
        })
        console.log(this.button)
    }

    handleInputValue(e) {
        this.setState({
            inputValue: e.target.value
        })
    }

    handleDeleteItem(index) {
        console.log(index);
        const lists = [...this.state.lists];
        lists.splice(index,1);
        this.setState({lists});
    }

    handleDelete(index) {
        const lists = [...this.state.lists];
        lists.splice(index,1);
        this.setState({lists});
    }

    getTodoListItem() {
        /* map 返回的是一个新的数组 */
        return (
            this.state.lists.map((item,index) => {
                // return <li key={index} onClick={this.handleDeleteItem.bind(this,index)}>{item}</li>
                return <TodoListItem content={item} key={index} index={index} setDelete={this.handleDelete}/>
            })
        )
    }
  render() {
      return (
        <Fragment>
            <label htmlFor="insertArae">输入文字</label>
            <input type="text" onChange={this.handleInputValue} value={this.state.inputValue} id="insertArae"/>
            {/* this.handleClick 中的this指向的是TodOlIST */}
            <button onClick={this.handleClick} ref={(btn) => {this.button = btn}}>add</button>
            <ul>
                {this.getTodoListItem()}
            </ul>
        </Fragment>
    );
  }
}

export default TodoList;
